<script setup>
import { User, Lock, Message } from "@element-plus/icons-vue";
import { ref, computed } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import {
  userRegisterService,
  userLoginService,
  sendVerificationCodeService,
} from "@/api/user.js";

// 路由控制
const router = useRouter();

// 表单显示控制
const isRegister = ref(false);

// 数据模型
const registerData = ref({
  username: "",
  password: "",
  rePassword: "",
  email: "",
  code: "",
});

// 清空数据
const clearRegisterData = () => {
  registerData.value = {
    username: "",
    password: "",
    rePassword: "",
    email: "",
    code: "",
  };
};

// 二次密码校验
const checkRePassword = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请再次确认密码"));
  } else if (value !== registerData.value.password) {
    callback(new Error("两次输入的密码不一致"));
  } else {
    callback();
  }
};

// 表单校验规则
const rules = ref({
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "邮箱格式不正确", trigger: "blur" },
  ],
  code: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { len: 6, message: "验证码为6位数字", trigger: "blur" },
  ],
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 16, message: "长度应为3-16个字符", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 5, max: 16, message: "长度应为5-16个字符", trigger: "blur" },
  ],
  rePassword: [{ validator: checkRePassword, trigger: "blur" }],
});

// 验证码倒计时
const codeCountdown = ref(0);
const codeTimer = ref(null);
const codeButtonText = computed(() =>
  codeCountdown.value > 0 ? `${codeCountdown.value}秒后重试` : "获取验证码"
);

// 发送验证码
const sendRegisterCode = async () => {
  try {
    if (
      !/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(registerData.value.email)
    ) {
      ElMessage.warning("请输入有效的邮箱地址");
      return;
    }

    await sendVerificationCodeService({
      email: registerData.value.email,
      type: "register",
    });

    ElMessage.success("验证码已发送");
    codeCountdown.value = 60;
    codeTimer.value = setInterval(() => {
      codeCountdown.value--;
      if (codeCountdown.value <= 0) clearInterval(codeTimer.value);
    }, 1000);
  } catch (error) {
    ElMessage.error(error.response?.data?.message || "发送失败");
  }
};

// 注册功能
const register = async () => {
  try {
    const result = await userRegisterService({
    ...registerData.value,
    type: "register", // 关键参数
  });

  console.log(code)
  if (result.code === 200) {
    ElMessage.success("注册成功，请打开确认邮件"); // Element提示
    clearRegisterData();
    router.push("/login");
  }
  } catch (error) {
    
  }
  
};

// 登录功能
const login = async () => {
  try {
    const result = await userLoginService({
      identifier: registerData.value.username,
      password: registerData.value.password,
    });

    if (result.code === 200) {
      ElMessage.success("登录成功");
      router.push("/components/AMap");
    } else {
      ElMessage.error(result.message || "登录失败");
    }
  } catch (error) {
   
  }
};
// 跳转忘记密码
const navigateToForgotPassword = () => {
  router.push("/forgot-password");
};
</script>

<template>
  <el-row class="login-page">
    <el-col :span="12" class="bg"></el-col>
    <el-col :span="6" :offset="3" class="form">
      <!-- 注册表单 -->
      <el-form
        v-if="isRegister"
        ref="registerForm"
        :model="registerData"
        :rules="rules"
        size="large"
        autocomplete="off"
      >
        <el-form-item>
          <h1>注册</h1>
        </el-form-item>

        <el-form-item prop="username">
          <el-input
            v-model="registerData.username"
            :prefix-icon="User"
            placeholder="请输入用户名"
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="registerData.password"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>

        <el-form-item prop="rePassword">
          <el-input
            v-model="registerData.rePassword"
            :prefix-icon="Lock"
            type="password"
            placeholder="请再次输入密码"
            show-password
          />
        </el-form-item>

        <el-form-item prop="email">
          <el-input
            v-model="registerData.email"
            :prefix-icon="Message"
            placeholder="请输入邮箱"
          />
        </el-form-item>

        <el-form-item prop="code" class="code-input">
          <el-input v-model="registerData.code" placeholder="请输入验证码">
            <template #append>
              <el-button
                :disabled="codeCountdown > 0"
                @click="sendRegisterCode"
              >
                {{ codeButtonText }}
              </el-button>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button class="button" type="primary" @click="register">
            立即注册
          </el-button>
        </el-form-item>

        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = false">
            ← 返回登录
          </el-link>
        </el-form-item>
      </el-form>

      <!-- 登录表单 -->
      <el-form
        v-else
        ref="loginForm"
        :model="registerData"
        :rules="rules"
        size="large"
        autocomplete="off"
      >
        <el-form-item>
          <h1>登录</h1>
        </el-form-item>

        <el-form-item prop="username">
          <el-input
            v-model="registerData.username"
            :prefix-icon="User"
            placeholder="请输入用户名"
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="registerData.password"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>

        <el-form-item class="flex">
          <div class="flex">
            <el-checkbox>记住我</el-checkbox>
            <el-link
              type="primary"
              :underline="false"
              @click="navigateToForgotPassword"
            >
              忘记密码
            </el-link>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button class="button" type="primary" @click="login">
            立即登录
          </el-button>
        </el-form-item>

        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = true">
            注册新账号 →
          </el-link>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<style lang="scss" scoped>
.login-page {
  height: 100vh;
  background-color: #fff;

  .bg {
    background: url("@/assets/logo2.png") no-repeat 60% center / 240px auto,
      url("@/assets/login_bg.jpg") no-repeat center / cover;
    border-radius: 0 20px 20px 0;
  }

  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;

    .button {
      width: 100%;
      padding: 12px;
      font-size: 16px;
    }

    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }

    .code-input :deep(.el-input-group__append) {
      padding: 0;
      .el-button {
        height: 100%;
        padding: 0 20px;
      }
    }
  }
}
</style>